#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    server = new QTcpServer(this);
    server->listen(QHostAddress::Any,9000);
    connect(server,&QTcpServer::newConnection,this,&MainWindow::newConnectionSlot);

    dataBase = new database;
    // query = QSqlQuery(dataBase->dataBase);

    qDebug()<<"服务器初始化完毕";
}

MainWindow::~MainWindow()
{
    delete ui;
    delete dataBase;
}

void MainWindow::newConnectionSlot()
{
    qDebug()<<"有客户端连接上了";
    QTcpSocket * socket = server->nextPendingConnection();
    clientList.push_back(socket);
    connect(socket,&QTcpSocket::readyRead,this,&MainWindow::readyReadSlot);
}

void MainWindow::readyReadSlot()
{
    for(int i = 0; i < clientList.count(); i++)
    {
        if(0 == clientList[i]->state())
        {
            clientList.removeAt(i);     //将下标为i的客户端移除
        }
    }
    for(int i = 0; i < clientList.count(); i++)
    {
        if(0 != clientList[i]->bytesAvailable())
        {
            QString msg = QString::fromLocal8Bit(clientList[i]->readAll());
            qDebug()<<msg;
            if(true == msg.contains(' '))
            {
                msg = dataBase->excuSql(msg);
            }
            else
            {
                QString query = QString("SELECT * FROM user WHERE username = '%1'").arg(msg);
                QSqlQuery sqlQuery(query);
                if(true == sqlQuery.next())
                    msg = "exist";
                else if(false == sqlQuery.next())
                    msg = "no exist";
            }
            clientList[i]->write(msg.toLocal8Bit());
        }
    }
}
